import { Module, VuexModule, getModule, Mutation, Action } from 'vuex-module-decorators'
import store from '@/store'

export interface Product {
  id: number
  title: string
  number: number
}

export interface CartState {
  // 购物车列表
  cartList: Product[]
}

@Module({ name: 'cart', store, dynamic: true })
export class Cart extends VuexModule implements CartState {
  cartList: Product[] = []

  get typeCount() {
    return this.cartList.length
  }

  get count() {
    return this.cartList.reduce((prev, current) => prev + current.number, 0)
  }

  @Mutation
  SetCartList(list: Product[]) {
    this.cartList = list
  }

  @Mutation
  AddCartList(product: Product) {
    const findProduct = this.cartList.find(item => item.id === product.id)
    if (findProduct) {
      findProduct.number++
    } else {
      product.number = typeof product.number === 'number' && product.number > 1 ? product.number : 1
      this.cartList.push(product)
    }
  }

  @Mutation
  ReduceCartList(product: Product) {
    const findProductIndex = this.cartList.findIndex(item => item.id === product.id)
    const findProduct = this.cartList[findProductIndex]
    if (findProduct) {
      // 如果购物车数量大于1，则减少
      if (findProduct.number >= 1) {
        findProduct.number--
      }
      // 如果购物车数量小于等于0.则删除
      if (findProduct.number <= 0) {
        this.cartList.splice(findProductIndex, 1)
      }
    }
  }

  @Action
  getCartList(): Promise<any> {
    return new Promise((resolve: Function) => {
      setTimeout(() => {
        this.SetCartList([
          {
            id: 1,
            title: '电脑',
            number: 2,
          },
        ])
        resolve()
      }, 1500)
    })
  }
}

export const CartModule = getModule(Cart)
